﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Records;

namespace ZhonTai.Admin.Core.Helpers
{
    public static class SimpleLicenseGenerator
    {
        public static void CreateLicenseFile(string customerName, int validDays,string machineId, string outputPath = "license.lic")
        {
            var licenseInfo = new LicenseInfo
            {
                ProductKey = Guid.NewGuid().ToString(),
                ExpireDate = DateTime.Now.AddDays(validDays),
                MachineId = machineId,
                CustomerName = customerName,
                Status = "Valid"
            };

            string json = JsonSerializer.Serialize(licenseInfo, new JsonSerializerOptions
            {
                WriteIndented = true
            });

            File.WriteAllText(outputPath, json);
            Console.WriteLine($"License文件已生成: {outputPath}");
            Console.WriteLine($"机器ID: {machineId}");
            Console.WriteLine($"有效期至: {licenseInfo.ExpireDate}");
        }

        public static string GetMachineId()
        {
            string cpuId = "UnknownCPU";
            string boardId = "UnknownBoard";

            try
            {
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT ProcessorId FROM Win32_Processor"))
                using (ManagementObjectCollection collection = searcher.Get())
                {
                    foreach (ManagementObject obj in collection)
                    {
                        cpuId = obj["ProcessorId"]?.ToString() ?? "UnknownCPU";
                        break;
                    }
                }

                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_BaseBoard"))
                using (ManagementObjectCollection collection = searcher.Get())
                {
                    foreach (ManagementObject obj in collection)
                    {
                        boardId = obj["SerialNumber"]?.ToString() ?? "UnknownBoard";
                        break;
                    }
                }
            }
            catch
            {
                cpuId = Environment.MachineName;
                boardId = Environment.UserName;
            }

            return $"{cpuId}_{boardId}".GetHashCode().ToString("X");
        }
    }
}
